package com.revengemission.sso.oauth2.client.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class TokenController {

    private final OAuth2AuthorizedClientService authorizedClientService;

    public TokenController(OAuth2AuthorizedClientService authorizedClientService) {
        this.authorizedClientService = authorizedClientService;
    }

    /**
     * 验证token是否有效的端点
     */
    @GetMapping("/validate-token")
    public ResponseEntity<Map<String, Object>> validateToken(Authentication authentication) {
        Map<String, Object> result = new HashMap<>();
        
        // 如果用户已认证，则token有效
        if (authentication != null && authentication.isAuthenticated()) {
            if (authentication instanceof OAuth2AuthenticationToken) {
                OAuth2AuthorizedClient client = authorizedClientService
                    .loadAuthorizedClient(
                        ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(),
                        authentication.getName());
                
                // 检查token是否存在和是否过期
                if (client != null && client.getAccessToken() != null && 
                    !client.getAccessToken().getExpiresAt().isBefore(java.time.Instant.now())) {
                    result.put("valid", true);
                    result.put("username", authentication.getName());
                    result.put("authorities", authentication.getAuthorities());
                    return ResponseEntity.ok(result);
                }
            }
        }
        
        // 认证失败或token无效
        result.put("valid", false);
        result.put("message", "未认证或认证已过期");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
    }
} 